package com.nuckly.news.ui.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nuckly.news.data.News
import com.nuckly.news.data.ResultWrapper
import com.nuckly.news.data.api.ApiResponse
import com.nuckly.news.data.api.NewsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NewsFeedViewModel @Inject constructor(private val repository: NewsRepository) : ViewModel() {

    private val newsFeedsLiveData = MutableLiveData<ResultWrapper<List<News>?>>()

    fun getNewsFeeds() = newsFeedsLiveData

    init {
        loadNewsFeeds()
    }

    private fun loadNewsFeeds() {
        viewModelScope.launch {
            newsFeedsLiveData.postValue(ResultWrapper.Loading)
            try {
                val response = repository.fetchNewsFeeds()
                val apiResponse: ApiResponse<List<News>>? = response.body()
                if (response.isSuccessful && apiResponse != null) {
                    if (apiResponse.isSuccess()) {
                        newsFeedsLiveData.postValue(ResultWrapper.Success(apiResponse.articles))
                    } else {
                        newsFeedsLiveData.postValue(ResultWrapper.Error("unable to fetch news"))
                    }
                } else {
                    newsFeedsLiveData.postValue(ResultWrapper.Error("unable to fetch news"))
                }
            } catch (exception: Exception) {
                newsFeedsLiveData.postValue(ResultWrapper.Error("unable to fetch news"))
            }
        }
    }

}